package com.tramy.cnpush;

import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;

import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.module.annotations.ReactModule;
import com.huawei.hms.aaid.HmsInstanceId;
import com.huawei.hms.common.ApiException;
import com.tramy.cnpush.utils.CallBackUtils;

@ReactModule(name = HUAWEIPushModule.NAME)
public class HUAWEIPushModule extends ReactContextBaseJavaModule {

    public static final String NAME = "HUAWEIPush";

    public HUAWEIPushModule(ReactApplicationContext reactContext) {
        super(reactContext);
    }

    @Override
    @NonNull
    public String getName() {
        return NAME;
    }

    @SuppressLint("StaticFieldLeak")
    @ReactMethod
    public void register(String appId,
                         Callback callback) {
        new AsyncTask<Integer, Integer, String>() {

            @Override
            protected String doInBackground(Integer... integers) {
                String tokenScope = "HCM";
                CallBackUtils.trustCallback(callback);
                try {
                    String token = HmsInstanceId
                        .getInstance(getReactApplicationContext().getApplicationContext())
                        .getToken(appId, tokenScope);
                    if (!TextUtils.isEmpty(token)) {
                        CallBackUtils.trustCallback(null);
                        callback.invoke(token);
                    }
                }catch (ApiException e) {
                    Log.e("HuaweiPush", e.toString());
                }
                return "";
            }

        }.execute();
    }

    @SuppressLint("StaticFieldLeak")
    @ReactMethod
    public void unRegister(String appId) {
        new AsyncTask<Integer, Integer, String>() {

            @Override
            protected String doInBackground(Integer... integers) {
                try {
                    String tokenScope = "HCM";
                    HmsInstanceId
                        .getInstance(getReactApplicationContext().getApplicationContext())
                        .deleteToken(appId, tokenScope);
                }catch (ApiException e) {
                    Log.e("HuaweiPush", e.toString());
                }
                return "";
            }

        }.execute();
    }

}
